import json
#encoding:utf-8
import time
from urllib.request import Request, urlopen
import requests

##########################设置房间号###############################
ROOM = ""
###########################设置SENDKEY############################
KEY1 = ""
#KEY2 = ""
###########################设置UP的名字############################
NAME = ""
##################################################################

api = "https://api.live.bilibili.com/room/v1/Room/room_init?id={}".format(ROOM)

#直播间状态，主播来这波来全杀了
live_room = 0

#获取直播状态
def state():
    firefox_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
    request = Request( api, headers=firefox_headers )
    html = urlopen(request)
    data = html.read()
    strs = str(data)
    html.close()
    #print(strs)
    return strs.find('"live_status":1')

#推送开播信息到微信
def sendMsg(key):
    data={
        "title" : "{}开播啦".format(NAME),
        "desp" :"你喜欢的主播开播啦"
    }
    url = 'https://sctapi.ftqq.com/{}.send'.format(key)
    res = requests.post(url = url,data=data)

#live判断是否在播
def live():
    #升级为全局变量
    global live_room
    global live_status
    
    #获取直播状态
    live_status = state()

    #live_room状态为0且不在播，表示不在播
    if live_room == 0 and live_status ==  -1:
        print("非常遗憾，还没播")
        
    #live_room状态为1且在直播，表示正在播
    if live_room == 1 and live_status != -1:
        print("在直播呢，还不去")
        
    #live_room状态为1但下播了，表示刚下播，修改live_room状态
    if live_room == 1 and live_status ==  -1:
        live_room = 0
        print("下播咯，拜拜了您勒")
        
    #live_room状态为0但在直播，表示刚开播，修改live_room状态    
    if live_room == 0 and live_status != -1:
        live_room = 1
        sendMsg(KEY1)
        #sendMsg(KEY2)
        print("过年了过年了，直播了")

#循环调用live函数
second = 60
while True:
    live()
    time.sleep(second)